import { HFiveMemberAppObjProcess } from '@/api/public.js'
import { useTableStore } from '@/store/table.js';
import { useCardStore } from '@/store/card.js';
// 正确的引入方式
// import jweixin from '@/js-sdk/jweixin-module';
import wx from "weixin-js-sdk";

//所在环境
let client = null
// #ifdef MP-WEIXIN
client = 1
// #endif

// #ifdef H5
client = isWeixinClient() ? 2 : 6
// #endif

// #ifdef APP-PLUS
client = 3;
uni.getSystemInfo({
	success: res => {
		client = res.platform == 'ios' ? 3 : 4;
	},
	fail: res => {
		client = 3
	}
})
// #endif
export {
	client
}


//节流
export const trottle = (func, time = 1000, context) => {
	let previous = new Date(0).getTime()
	return function(...args) {
		let now = new Date().getTime()
		if (now - previous > time) {
			func.apply(context, args)
			previous = now
		}
	}
}


//防抖
export const debounce = (func, time = 1000, context) => {
	let timer = null
	return function(...args) {
		if (timer) {
			clearTimeout(timer)
		}
		timer = setTimeout(() => {
			timer = null
			func.apply(context, args)
		}, time)
	}
}

// 搜索防抖
let antiShakeTimer = null;
export const antiShake = (fn, time) => {
	if (antiShakeTimer) {
		clearTimeout(antiShakeTimer);
		antiShakeTimer = null;
	}

	antiShakeTimer = setTimeout(() => {
		fn();
		clearTimeout(antiShakeTimer);
		antiShakeTimer = null;
	}, time);
}

/* 
 * 路径参数提取
 */
export function _ExtractParamsFromPath(path) {
	const queryString = path.split('?')[1]; // 获取问号后的部分
	const paramPairs = queryString.split('&'); // 拆分参数对
	const params = {}; // 创建新的对象
	for (let i = 0; i < paramPairs.length; i++) {
		const pair = paramPairs[i].split('='); // 拆分键和值
		const key = pair[0];
		const value = pair[1];
		params[key] = value; // 填入对象
	}

	return params;
}

// 扫码SDK---IOS&安卓环境判断 
export async function getWeChatJsSDKConfig() {
	// if(!uni.getStorageSync('token')){
	// 	return
	// }
	let url = ""
	let u = window.navigator.userAgent;
	let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
	//Ios地址和安卓不一致
	if (isiOS) {
		url = uni.getStorageSync('IOS_URL')
	} else {
		url = window.location.href
	}
	const SDKConfig = await HFiveMemberAppObjProcess({
		functionName: "WeChatJsSDKConfig_H5",
		contentData: { "url": url }
	})
	return SDKConfig
}


export const _FormatNumber = (num) => {
	let numStr = null;
	if (num === undefined || num === null || num === "" || num === NaN) {
		numStr = num;
	} else {
		numStr = num.toString();

		if (numStr.indexOf(".") !== -1 && numStr.split(".")[1].length === 1) {
			numStr += "0";
		} else if (numStr.indexOf(".") === -1) {
			numStr += ".00";
		}
	}
	numStr = parseFloat(numStr).toFixed(2)

	return numStr;
}
//判断是否为微信环境
export function isWeixinClient() {
	// #ifdef H5
	var ua = navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		//这是微信环境
		return true;
	} else {
		//这是非微信环境
		return false;
	}
	// #endif
	// #ifndef H5
	return false
	// #endif
}

//判断是否为安卓环境
export function isAndroid() {
	let u = navigator.userAgent;
	return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
}

//获取url后的参数  以对象返回
export function strToParams(str) {
	var newparams = {}
	for (let item of str.split('&')) {
		newparams[item.split('=')[0]] = item.split('=')[1]
	}
	return newparams
}

//重写encodeURL函数
export function urlencode(str) {
	str = (str + '').toString();
	return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
	replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}


//一维数组截取为二维数组
export function arraySlice(data, array = [], optNum = 10) {
	data = JSON.parse(JSON.stringify(data))
	if (data.length <= optNum) {
		data.length > 0 && array.push(data);
		return array;
	}
	array.push(data.splice(0, optNum));
	return arraySlice(data, array, optNum);
}

//对象参数转为以？&拼接的字符
export function paramsToStr(params) {
	let p = '';
	if (typeof params == 'object') {
		p = '?'
		for (let props in params) {
			p += `${props}=${params[props]}&`
		}
		p = p.slice(0, -1)
	}
	return p
}



// 获取wxml元素

export function getRect(selector, all, context) {
	return new Promise(function(resolve) {
		let qurey = uni.createSelectorQuery();

		if (context) {
			qurey = uni.createSelectorQuery().in(context);
		}

		qurey[all ? 'selectAll' : 'select'](selector).boundingClientRect(function(rect) {
			if (all && Array.isArray(rect) && rect.length) {
				resolve(rect);
			}
			if (!all && rect) {
				resolve(rect);
			}
		}).exec();
	});
}


// 轻提示
export function toast(info = {}, navigateOpt) {
	let title = info.title || ''
	let icon = info.icon || 'none'
	let endtime = info.endtime || 2000
	if (title) uni.showToast({
		title: title,
		icon: icon,
		duration: endtime
	})
	if (navigateOpt != undefined) {
		if (typeof navigateOpt == 'object') {
			let tab = navigateOpt.tab || 1,
				url = navigateOpt.url || '';
			switch (tab) {
				case 1:
					//跳转至 table
					setTimeout(function() {
						uni.switchTab({
							url: url
						})
					}, endtime);
					break;
				case 2:
					//跳转至非table页面
					setTimeout(function() {
						uni.navigateTo({
							url: url,
						})
					}, endtime);
					break;
				case 3:
					//返回上页面
					setTimeout(function() {
						uni.navigateBack({
							delta: parseInt(url),
						})
					}, endtime);
					break;
				case 4:
					//关闭当前所有页面跳转至非table页面
					setTimeout(function() {
						uni.reLaunch({
							url: url,
						})
					}, endtime);
					break;
				case 5:
					//关闭当前页面跳转至非table页面
					setTimeout(function() {
						uni.redirectTo({
							url: url,
						})
					}, endtime);
					break;
			}

		} else if (typeof navigateOpt == 'function') {
			setTimeout(function() {
				navigateOpt && navigateOpt();
			}, endtime);
		}
	}
}

//菜单跳转
export function menuJump(item) {
	const {
		is_tab,
		link,
		link_type
	} = item
	switch (link_type) {
		case 1:
			// 本地跳转
			if (is_tab) {
				uni.switchTab({
					url: link
				});
				return;
			}
			uni.navigateTo({
				url: link
			});
			break;

		case 2:
			// webview
			uni.navigateTo({
				url: "/pages/webview/webview?url=" + link
			});
			break;

		case 3: // tabbar

	}
}

export function uploadFile(path, options) {
	let baseURL = ''
	const {
		header,
		name
	} = options || {}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: baseURL + '/api/file/formimage',
			filePath: path,
			name: name || 'file',
			header: {
				// token: store.getters.token,
				...header
				// version: '1.2.1.20210717'
			},
			fileType: 'image',
			cloudPath: '',
			success: res => {
				try {
					console.log(path)
					console.log('uploadFile res ==> ', res)
					let data = JSON.parse(res.data);

					if (data.code == 1) {
						resolve(data.data);
					} else {
						reject()
					}
				} catch (e) {
					console.log(e)
					reject()
				}
			},
			fail: (err) => {
				console.log(err)
				reject()
			}
		});
	});


}

//当前页面

export function currentPage() {
	let pages = getCurrentPages();
	let currentPage = pages[pages.length - 1];
	return currentPage || {};
}

/* 
 * 补齐两位小数
 */
export function formatDecimal(num) {
	let numStr = null;
	if (num === undefined || num === null || num === "" || num === NaN) {
		numStr = num;
	} else {
		numStr = num.toString();
		// console.log(numStr, numStr.indexOf(".") === -1);
		if (numStr.indexOf(".") !== -1 && numStr.split(".")[1].length === 1) {
			numStr += "0";
		} else if (numStr.indexOf(".") === -1) {
			numStr += ".00";
		}
	}
	numStr = parseFloat(numStr).toFixed(2)
	// console.log('numStr',numStr)
	return numStr;
}

// H5复制方法
export function copy(str) {
	// #ifdef H5
	let aux = document.createElement("input");
	aux.setAttribute("value", str);
	document.body.appendChild(aux);
	aux.select();
	document.execCommand("copy");
	document.body.removeChild(aux);
	uni.showToast({
		title: "复制成功",
	})
	// #endif

	// #ifndef H5
	uni.setClipboardData({
		data: str.toString(),
	})
	// #endif
}


// #ifdef MP-WEIXIN
export function toLivePlayer(roomId) {
	wx.navigateTo({
		url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}`
	})
}
// #endif


// 隐藏中间内用*号代替 > frontLen为星号前的数据  > endLen为星号后的数据
export function plusXing(str, frontLen, endLen) {
	var len = str.length - frontLen - endLen;
	var xing = '';
	for (var i = 0; i < len; i++) {
		xing += '*';
	}
	return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
}

// 隐藏中间内用X号代替 > frontLen为星号前的数据  > endLen为星号后的数据
export function plusX(str, frontLen, endLen) {
	var len = str.length - frontLen - endLen;
	var xing = '';
	for (var i = 0; i < len; i++) {
		xing += 'X';
	}
	var result = str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
	return plusReplaceEmpty(result)
}

// 每4格存1空格 (str,num) num>>>动态number
export function plusReplaceEmpty(str) {
	// var result = str.replace(/\s/g, '').replace(/(.{4})/g, "$1 ");
	return str.replace(/\s/g, '').replace(/(.{4})/g, "$1 ")
}



// export const initStatusBarHeight = () => {}
// 初始化自定义导航栏头部距离
export const initStatusBarHeight = () => {
	let fixHeight = 0
	uni.getSystemInfo({
		success: (e) => {
			// #ifdef MP-WEIXIN 
			const custom = wx.getMenuButtonBoundingClientRect()
			const customBar = custom.bottom + custom.top - e.statusBarHeight
			// 单位转换 默认ui 750为基准
			const screenWidth = uni.getSystemInfoSync().screenWidth
			fixHeight = (750 * Number.parseInt(customBar)) / screenWidth
			// #endif  

			// #ifdef APP-PLUS  
			// #endif 

			// #ifdef H5
			// #endif  
		}
	})
	// console.log('fixHeight:',fixHeight)
	return fixHeight
}

// 扫桌台码 或者 桌台链接有该入参后，跟新服务端的桌台信息。  
export async function updateTableInfo(roomCode) {
	// 实际还有	'brandCode':'0004', 'orgCode':'0017'
	let modal = { "functionName": "UpdateCurrentRoom_H5", "contentData": { "roomCode": roomCode } }
	const tableInfo1 = await HFiveMemberAppObjProcess(modal)
	console.log('tableInfo1', tableInfo1)
	return tableInfo1;
}

// 前提要有roomCode 才可以查询 当前房台信息，包括低消等信息 
export async function initTableInfo() {
	const roomCode = uni.getStorageSync('tableInfo')?.code
	const storeTable = useTableStore();
	let modal = { "functionName": "GetRoomInfo_H5", "contentData": { "roomCode": roomCode } }
	const tableInfo2 = await HFiveMemberAppObjProcess(modal)
	console.log('tableInfo', tableInfo2)
	storeTable.SetTableInfo(tableInfo2)
	return tableInfo2;
}

// 当前房台信息（每次进入商品列表查询一次，判断是否有房台信息，如果没有则要扫码获取房台信息，如果有则直接进入点单页面）
export async function initTableInfoFinish() {
	let modal = { "functionName": "GetCurrentRoom_H5", "contentData": "" }
	const tableInfo3 = await HFiveMemberAppObjProcess(modal)
	console.log('tableInfo3', tableInfo3)
	if(tableInfo3 && tableInfo3.currentRoomCode){
		let obj = {
			code:tableInfo3.currentRoomCode,
			name:tableInfo3.currentRoomName
		}
		uni.setStorageSync('tableInfo',obj)
	}
	return tableInfo3; // 返回currentRoomCode 赋值给roomCode
}

// 单卡 信息 （默认第一张）
export async function initCardInfo() {
	uni.showLoading({
		title: '加载中...'
	});
	const storeCard = useCardStore();
	let cardsModal = { "functionName": "MemberInfo_H5", "contentData": "" }
	const catdList = await HFiveMemberAppObjProcess(cardsModal)
	const oneCardInfo = catdList[0]
	let shopInfo = uni.getStorageSync('shopInfo')
	if(shopInfo.isPriceVipPrice){  // isPriceVipPrice是否要有会员余额才可享受权益会员
		if(oneCardInfo.currentAmtAct > 0 && oneCardInfo.memberIsPayCard == 1){
			oneCardInfo.memberIsPayCard = 1
		}else{
			oneCardInfo.memberIsPayCard = 0
		}
	}
	storeCard.SetCardInfo(oneCardInfo)
	uni.hideLoading();
	// console.log('catdList', catdList)
	return oneCardInfo;
}

// 卡列表 信息 （切换卡操作） // 返回所有卡
export async function getCardInfoMore() {
	// uni.showLoading({
	// 	title: '加载中...'
	// });
	const storeCard = useCardStore();
	let cardsModal = { "functionName": "MemberInfo_H5", "contentData": "" }
	const catdList = await HFiveMemberAppObjProcess(cardsModal)
	// let oneCardInfo = {}
	// catdList.forEach((item) => {
	// 	if (nowCardInfo.code === item.code) {
	// 		oneCardInfo = item
	// 	}
	// })
	// storeCard.SetCardInfo(oneCardInfo)
	// uni.hideLoading();
	return catdList;
	// uni.showLoading({
	// 	title: '切换中...'
	// });
	// const storeCard = useCardStore();
	// let cardsModal = { "functionName": "MemberInfo_H5", "contentData": "" }
	// const catdList = await HFiveMemberAppObjProcess(cardsModal)
	// let oneCardInfo = {}
	// catdList.forEach((item) => {
	// 	if (nowCardInfo.code !== item.code) {
	// 		oneCardInfo = item
	// 	}
	// })
	// storeCard.SetCardInfo(oneCardInfo)
	// uni.hideLoading();
	// // console.log('catdList', catdList)
	// return oneCardInfo;
}

// 卡信息 （跟新当前卡的信息>>>类似 by id 查询）返回一张卡
export async function getCardInfoUpdate(nowCardInfo) {
	uni.showLoading({
		title: '加载中...'
	});
	const storeCard = useCardStore();
	let cardsModal = { "functionName": "MemberInfo_H5", "contentData": "" }
	const catdList = await HFiveMemberAppObjProcess(cardsModal)
	let oneCardInfo = {}
	catdList.forEach((item) => {
		if (nowCardInfo.code === item.code) {
			oneCardInfo = item
		}
	})
	storeCard.SetCardInfo(oneCardInfo)
	uni.hideLoading();
	return oneCardInfo;
}

export  function calculatePercentPrice(data) { // 计算比例价格
console.log(data,'groupedData');
	const groupedData = data.reduce((acc, item) => {
	  const { indexStr, itemType } = item;
	  
	  // 如果该 indexStr 的分组不存在，初始化它
	  if (!acc[indexStr]) {
	    acc[indexStr] = { ...item, children: [] }; // 创建主项对象，并初始化 children 数组
	  }
	
	  // 如果是子项，添加到对应的 children 数组中
	  if (itemType == 3) {
	    acc[indexStr].children.push(item);
	  }
	
	  return acc;
	}, {});
	const  calculateTotal = (dataArray) => {
		return dataArray.reduce((total, item) => {
		  if (item.orderQty !== undefined && item.salePrice !== undefined) {
			// 如果是最底层对象，计算 stepNum * salePrice 并添加到总和中
			return total + (Number(item.orderQty) * Number(item.salePrice));
		  } else {
			return total;
		  }
		}, 0);
	}
	// 计算比例价格的和
	const  calculatePrice = (dataArray)=>{
	    return dataArray.reduce((total, item) => {
	    if (item.percentPrice !== undefined) {
	        return total + item.percentPrice;
	    } else {
				return total;
			}
	    }, 0);
	}
	const  calculateVipPrice =(dataArray)=>{
	 return dataArray.reduce((total, item) => {
		if (item.vipPercentPrice !== undefined) {
	       return total + item.vipPercentPrice;
		} else {
	        return total;
	     }
	 }, 0);
	}
	
	const flattenChildren =(arr)=> {
	  const result = [];
	
	  arr.forEach(item => {
	    // 先将当前元素添加到结果数组
	    result.push(item);
	
	    // 如果有 children，将 children 中的元素提取到结果数组
	    if (item.children && Array.isArray(item.children)) {
	      result.push(...item.children); // 将 children 中的元素提取到结果数组
	      delete item.children; // 删除 children 属性
	    }
	  });
	
	  return result;
	}
	
	// Step 2: 将分组后的数据转换为数组
	const result = Object.values(groupedData);
	result.forEach(item=>{
		let toolPrice = calculateTotal(item.children)
		item.children.forEach(v=>{
			v.percentPrice = Math.floor(Number(item.salePrice) * Number(v.salePrice) * Number(v.orderQty) / Number(toolPrice))
			v.vipPercentPrice = Math.floor(Number(item.vipPrice) * Number(v.salePrice) * Number(v.orderQty) / Number(toolPrice))
		})
		let arrLength = item.children.length
		let percentPriceAll = calculatePrice(item.children)
		let percentVipPriceAll = calculateVipPrice(item.children)
		if(arrLength-1 >= 0){
		    item.children[arrLength-1].percentPrice = Number(item.children[arrLength-1].percentPrice) +(Number(item.salePrice) - Number(percentPriceAll))
		    item.children[arrLength-1].vipPercentPrice = Number(item.children[arrLength-1].vipPercentPrice) +(Number(item.vipPrice) - Number(percentVipPriceAll))
		}
	})
	// console.log(flattenChildren(result),'groupedData');
	return flattenChildren(result);
	

}


// 清除房台信息


// 微信支付
export function wxPay(opt) {
	return new Promise((reslove, reject) => {
		wx.ready(() => {
			wx.chooseWXPay({
				timestamp: opt
					.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
				nonceStr: opt.nonceStr, // 支付签名随机串，不长于 32 位 
				package: opt.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
				signType: opt.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
				paySign: opt.paySign, // 支付签名
				success: (res) => {
					reslove()
				},
				cancel: (res) => {
					reject()
				},
				fail: (res) => {
					reject()
				},
			});
		});
	})
}

// 
/**
 * 加法运算，避免数据相加小数点后产生多位数和计算精度损失。
 *
 * @param num1加数1 | num2加数2
 */
export function numAddFun(num1, num2) { 
    let strNum1 = num1.toString();
    let strNum2 = num2.toString(); 
    if (strNum1.includes('e') || strNum1.includes('E')) {
        strNum1 = (+strNum1).toFixed(20); 
    }
    if (strNum2.includes('e') || strNum2.includes('E')) {
        strNum2 = (+strNum2).toFixed(20);
    } 
    let baseNum1 = strNum1.split('.')[1] ? strNum1.split('.')[1].length : 0;
    let baseNum2 = strNum2.split('.')[1] ? strNum2.split('.')[1].length : 0; 
    let baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); 
    return (Math.round(num1 * baseNum) + Math.round(num2 * baseNum)) / baseNum;
}
// export function numAddFun(num1, num2) {
// 	console.log('啪啪啪:',num1,num2)
// 	var baseNum, baseNum1, baseNum2;
// 	try {
// 		baseNum1 = num1.toString().split(".")[1].length;
// 	} catch (e) {
// 		baseNum1 = 0;
// 	}
// 	try {
// 		baseNum2 = num2.toString().split(".")[1].length;
// 	} catch (e) {
// 		baseNum2 = 0;
// 	}
// 	baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
	 
	
// 	console.log('啪啪啪:',(num1 * baseNum + num2 * baseNum))
// 	console.log('啪啪啪:',baseNum)
// 	console.log('啪啪啪:',(num1 * baseNum + num2 * baseNum) / baseNum)
// 	return (num1 * baseNum + num2 * baseNum) / baseNum;
// };


/**
 * 乘法运算，避免数据相乘小数点后产生多位数和计算精度损失。
 *
 * @param num1被乘数 | num2乘数
 */
export function numMultiFun(num1, num2) {
	var baseNum = 0;
	try {
		baseNum += num1.toString().split(".")[1].length;
	} catch (e) {}
	try {
		baseNum += num2.toString().split(".")[1].length;
	} catch (e) {}
	return Number(num1.toString().replace(".", "")) * Number(num2.toString().replace(".", "")) / Math.pow(10, baseNum);
};


/**
 * 减法运算，避免数据相减小数点后产生多位数和计算精度损失。
 *
 * @param num1被减数 | num2减数
 */
export function numDiffFun(num1, num2) {
	var baseNum, baseNum1, baseNum2;
	var precision; // 精度
	try {
		baseNum1 = num1.toString().split(".")[1].length;
	} catch (e) {
		baseNum1 = 0;
	}
	try {
		baseNum2 = num2.toString().split(".")[1].length;
	} catch (e) {
		baseNum2 = 0;
	}
	baseNum = Math.pow(10, Math.max(baseNum1, baseNum2));
	precision = (baseNum1 >= baseNum2) ? baseNum1 : baseNum2;
	return ((num1 * baseNum - num2 * baseNum) / baseNum).toFixed(precision);
};


// 计算会员卡可抵扣的赠送金额  - 会员卡支付
export function memberPayGive(carPrice, userAmt, sendAmt, memberIsPayCardFlag, openVip, goodsList) {
	console.log(carPrice, userAmt, sendAmt, memberIsPayCardFlag, openVip, goodsList,'赠送金额调试');
	let canUsesendAmt = 0
	// let carPrice = data.carPrice // carPrice商品金额  -chu9.9购物车 
	// let userAmt = data.toolCard.currentAmt // userAmt用户本金
	// let sendAmt = data.toolCard.currentPresentAmt // sendAmt 用户赠送金额 
	if (uni.getStorageSync('shopInfo').preAmtUseRule.presentAmtUseType == '1') {
		canUsesendAmt = 0
	} else if (uni.getStorageSync('shopInfo').preAmtUseRule.presentAmtUseType == '2') {
		canUsesendAmt = carPrice * uni.getStorageSync('shopInfo').preAmtUseRule.useRate / 100
	} else if (uni.getStorageSync('shopInfo').preAmtUseRule.presentAmtUseType == '3') {
		let rule1 = JSON.parse(uni.getStorageSync('shopInfo').preAmtUseRule.saleAmtStepJson)
		let rule2 = JSON.parse(uni.getStorageSync('shopInfo').preAmtUseRule.saleLoopStepJson)
		if (uni.getStorageSync('shopInfo').preAmtUseRule.saleAmtStepJson == '1') {
			// 阶梯模式(可能有多个阶梯) 
			// 遍历每个规则，判断是否满足条件
			for (let i = 0; i < ruleList.length; i++) {
				let rule1 = ruleList[i];
				if (carPrice >= rule1.saleAmt) { // 车价大于等于当前阶梯金额
					if (rule1.uom == '元') { // 单位是“元”
						canUsesendAmt = rule1.canUse;
					} else if (rule1.uom == '%') { // 单位是“%”
						canUsesendAmt = carPrice * rule1.canUse / 100;
					}
				}

			}
		} else if (uni.getStorageSync('shopInfo').preAmtUseRule.saleAmtStepJson == '2') { // 循环模式 
			if (rule2.uom == '元') { // 达到目标金额
				canUsesendAmt = rule2.canUse * Math.floor(carPrice / rule2.saleAmt);
			} else if (rule2.uom == '%') {
				canUsesendAmt = rule2.canUse * Math.floor(carPrice / rule2.saleAmt) / 100 * carPrice
			}
		}

	} else if (uni.getStorageSync('shopInfo').preAmtUseRule.presentAmtUseType == '4') {
		// if (this.data.isVip || this.data.isOpenVip) {
		if (memberIsPayCardFlag || openVip) {
			goodsList.forEach(itemA => {
				// 在数组B中查找匹配的goodsCode
				let match = uni.getStorageSync('shopInfo').preAmtUseRule.preGoodsInfo.find(itemB => itemB
					.goodsCode === itemA.goodsCode);
				if (match) {
					// 如果找到了匹配的goodsCode，就将A中的vipPrice加到all上
					canUsesendAmt += itemA.vipPrice;
				}
			});
		} else {
			goodsList.forEach(itemA => {
				// 在数组B中查找匹配的goodsCode
				let match = uni.getStorageSync('shopInfo').preAmtUseRule.preGoodsInfo.find(itemB => itemB
					.goodsCode === itemA.goodsCode);
				if (match) {
					// 如果找到了匹配的goodsCode，就将A中的salePrice加到all上
					canUsesendAmt += itemA.salePrice;
				}
			});
		}
	} else if (uni.getStorageSync('shopInfo').preAmtUseRule.presentAmtUseType == '5') {
		if(sendAmt == 0){
			canUsesendAmt = 0
		}else{
			// canUsesendAmt = (carPrice - canUsesendAmt) * sendAmt / userAmt
			canUsesendAmt = carPrice * sendAmt / (sendAmt + userAmt) 
		}
		
	}
	
	if (sendAmt <= canUsesendAmt) {  // 如果会员赠送金额不足
		canUsesendAmt = Number(_FormatNumber(sendAmt))
	} else {
		canUsesendAmt = Number(_FormatNumber(canUsesendAmt))
	}
	console.log(canUsesendAmt);
	return canUsesendAmt
}


// 计算payList  (结算时后端需要的数据结构)
export function payListFun(payViewList,payTotalInfo,goodsList) { 
	let payListResult = []
	payViewList.forEach((item, index) => {
		let payModal = {
			"payType": "",
			"totalAmt": 0,
			"payAmt": 0, //
			"prePayAmt": 0, //
			"giveChange": 0, //不管
			"smallChange": 0, // 不管
			"memberCode": uni.getStorageSync('cardInfo').code,
			"memberName": uni.getStorageSync('cardInfo').carName,
			"memberMobile": uni.getStorageSync('userInfo').mobile,
			"memberOpenId": uni.getStorageSync('userInfo').openId, // 用户手机
			"payPreAmtRate": uni.getStorageSync('shopInfo').preAmtUseRule.useRate / 100
		}
		// 支付方式的集合  013 金币支付  004会员卡  002微信 003支付宝  005消费券  他人无需 
		if (item.checkPay) {
			if (item.name === '金币支付') {
				payModal.payType = '013'
				payModal.totalAmt = payTotalInfo.useGoldHad
				payModal.payAmt = payTotalInfo.useGoldHad
				payListResult.push(payModal)
			}
			if (item.name === '会员卡支付') {
				let presentAmt = uni.getStorageSync("cardInfo")?.currentPresentAmt || 0
				let currentAmt = uni.getStorageSync("cardInfo").currentAmt || 0
				let memberIsPayCardFlag = false
				if (uni.getStorageSync('cardInfo').memberIsPayCard === "1") {
					memberIsPayCardFlag = true
				} 
				payModal.payType = '004'
				payModal.prePayAmt = memberPayGive(payTotalInfo.totalPay, currentAmt, presentAmt, memberIsPayCardFlag, payTotalInfo.openVip, goodsList) // 赠送金额 !!!!!!!
				payModal.totalAmt = payTotalInfo.emberPayDiff
				payModal.payAmt = payTotalInfo.emberPayDiff
				payListResult.push(payModal)
			}
		}
	})
	// 补充 优惠券
	if (payTotalInfo.memberTicketCode) {
		let payModal = {
			"payType": "004",
			"totalAmt": payTotalInfo.ticketTotal,
			"payAmt": payTotalInfo.ticketTotal,
			"prePayAmt": 0, // 赠送金额
			"giveChange": 0, //不管
			"smallChange": 0, // 不管
			"memberCode": uni.getStorageSync('cardInfo').code,
			"memberName": uni.getStorageSync('cardInfo').carName,
			"memberMobile": uni.getStorageSync('userInfo').mobile,
			"memberOpenId": uni.getStorageSync('userInfo').openId, // 用户手机
			"payPreAmtRate": uni.getStorageSync('shopInfo').preAmtUseRule.useRate / 100
		}
		payListResult.push(payModal)
	}
	return payListResult 
}

// 支付方式 判定 - 暂时不用
export async function toPayTypeFun(getPatWayList,payTotalInfo,resultOrder,goodsList) {
	let resultType = 0
	let patWayList = getPatWayList.filter(item => item.checkPay).map(item => item.name)  
	let detailList = resultOrder.dataList.map(item => item.itemCode).join(','); 
	if (patWayList.includes('支付宝支付') ) { 
		let modalRec = {
			"functionName": "TemporaryOrderPay_H5",
			"contentData": {
				"cashUser": "",
				"consumeCode": resultOrder.consumeCode,
				"detailList": detailList, //商品 itemCode
				"isVip": storeCardInfo.value.memberIsPayCard === '1' || payTotalInfo.openVip ? true : false,
				"memberCode": uni.getStorageSync('userInfo').userCode, // userId
				"memberTicketCode": payTotalInfo.memberTicketCode, // 使用优惠券卡号 , 号拼接 
				"payBatchCode": "", // 支付批次号 - 暂不处理
				"payList": payListFun(payTotalInfo,goodsList), // 金币支付-组合支付有关
				"payUser": "", // 付款人(代付)，（服务员） - 传空
				"orderAmt": storeCardInfo.value.memberIsPayCard === '1' || payTotalInfo.openVip ? payTotalInfo.vipPriceTotal : payTotalInfo.salePriceTotal,  
				"realPayAmt": storeCardInfo.value.memberIsPayCard === '1' || payTotalInfo.openVip ? payTotalInfo.vipPriceTotal : payTotalInfo.salePriceTotal, 
				"roomCode": uni.getStorageSync('tableInfo').code, // "0017001",  
				"serviceAmt": [] // 总的原价格 - 会员折扣优惠 = 差价
			}
		}
		const resultRec = await HFiveMemberAppObjProcess(modalRec) // console.log('resultRec：', resultRec) 
		if(patWayList.includes('金币支付') || patWayList.includes('会员卡支付')){ 
			resultType = 2
		}else{ 
			resultType = 1 
		}
	}if (patWayList.includes('微信支付') ) { 
		let modalRec = {
			"functionName": "TemporaryOrderPay_H5",
			"contentData": {
				"cashUser": "",
				"consumeCode": resultOrder.consumeCode,
				"detailList": detailList, //商品 itemCode
				"isVip": storeCardInfo.value.memberIsPayCard === '1' || payTotalInfo.openVip ? true : false,
				"memberCode": uni.getStorageSync('userInfo').userCode, // userId
				"memberTicketCode": payTotalInfo.memberTicketCode, // 使用优惠券卡号 , 号拼接 
				"payBatchCode": "", // 支付批次号 - 暂不处理
				"payList": payListFun(payTotalInfo,goodsList), // 金币支付-组合支付有关
				"payUser": "", // 付款人(代付)，（服务员） - 传空
				"orderAmt": storeCardInfo.value.memberIsPayCard === '1' || payTotalInfo.openVip ? payTotalInfo.vipPriceTotal : payTotalInfo.salePriceTotal,  
				"realPayAmt": storeCardInfo.value.memberIsPayCard === '1' || payTotalInfo.openVip ? payTotalInfo.vipPriceTotal : payTotalInfo.salePriceTotal, 
				"roomCode": uni.getStorageSync('tableInfo').code, // "0017001",  
				"serviceAmt": [] // 总的原价格 - 会员折扣优惠 = 差价
			}
		}
		const resultRec = await HFiveMemberAppObjProcess(modalRec) // console.log('resultRec：', resultRec) 
		if(patWayList.includes('金币支付') || patWayList.includes('会员卡支付')){ 
			resultType = 4
		}else{ 
			resultType = 3
		}
	} else if (patWayList.includes('找人代付')) {  
		if(patWayList.includes('金币支付') || patWayList.includes('会员卡支付')){
			// toPublicPaySelect(resultOrder,2)  // 临时买单
			// otherReplacePay(resultOrder)
			resultType = 6
		}else{
			// otherReplacePay(resultOrder)
			resultType = 5
		}
	}else if (patWayList.includes('会员卡支付') || patWayList.includes('金币支付')) {  
		// toPublicPaySelect(resultOrder,1) 
		resultType = 7
	} else{
		// 优惠券直接全部支付了
		// toPublicPaySelect(resultOrder,1) 
		resultType = 7
	}  
	// 1：支付宝  2：支付宝+临时买单  3：微信 4：微信+临时买单  5：找人代付   6：找人代付+临时买单  7 买单
	return resultType
} 
 
 
		